package xproto

import (
	"fmt"
	"path/filepath"
	"strconv"
	"strings"

	"github.com/dontls/xproto/internal"
	uuid "github.com/satori/go.uuid"
)

// contextID 生成管理GUID
func contextID(args ...string) string {
	if len(args) > 1 && args[1] != "" {
		return args[0] + "." + args[1]
	}
	return args[0]
}

// up-1-filename
// up-文件类型-文件名
// FileSess 文件传输会话号
func FileSess(r *FileTransfer) string {
	ss := strconv.Itoa(r.FileType) + "@" + r.FileName
	if r.Action == ActUpload {
		ss = "file://" + ss
		r.FileName = filepath.Base(r.FileName)
	}
	return ss
}

func FileOfSess(ss string) (r FileTransfer) {
	r.Action = ActDownload
	if strings.HasPrefix(ss, "file://") {
		r.Action = ActUpload
		ss = ss[7:]
	}
	arrs := strings.Split(ss, "@")
	if len(arrs) > 1 {
		r.FileType, _ = strconv.Atoi(arrs[0])
		r.FileName = arrs[1]
	}
	if r.Action == ActDownload {
		r.FileName = filepath.Base(r.FileName)
	}
	return
}

// UUID 生成Guid字串
func UUID() string {
	u := uuid.NewV4()
	return u.String()
}

func NewUUID(s *string) {
	if *s == "" {
		*s = UUID()
	}
}

func alarmUUID(a *Alarm) {
	if a.UUID != "" {
		return
	}
	if a.StartTime == "" {
		a.StartTime = a.DTU
	}
	tt := internal.ToUnixTime(a.StartTime)
	zerol := 16 - len(a.DeviceNo)
	a.UUID = fmt.Sprintf("%10d%03d%03d%0*d%s", tt, a.Type, a.SubType, zerol, 0, a.DeviceNo)
}
